<template>
	<baseDialog ref="dialogRef" :title="dialogTitle" width="600px" @confirm="handleSubmit" @close="handleClose">
		<el-form ref="formRef" :model="formData" label-width="100px" :rules="rules">
			<el-form-item label="栏目名称：" prop="name">
				<div class="w-80">
					<el-input v-model="formData.name" placeholder="请输入栏目名称" clearable />
				</div>
			</el-form-item>
			<el-form-item label="上级栏目：" prop="pid">
				<el-cascader
					:options="cateOptions"
					:props="{ multiple: false, checkStrictly: true, emitPath: false, value: 'id', label: 'name' }"
					placeholder="请选择上级栏目"
					clearable
					class="w-80"
					v-model="formData.pid"
				>
					<template #default="{ data }">
						<span>{{ data.name }}</span>
					</template>
				</el-cascader>
			</el-form-item>
			<el-form-item label="排序：" prop="sort">
				<div>
					<el-input-number v-model="formData.sort" :min="0" :max="9999" />
					<div class="el-form-tips">默认为0， 数值越大越排前</div>
				</div>
			</el-form-item>
			<el-form-item label="状态：">
				<el-radio-group v-model="formData.status">
					<el-radio :label="1">显示</el-radio>
					<el-radio :label="0">隐藏</el-radio>
				</el-radio-group>
			</el-form-item>
		</el-form>
	</baseDialog>
</template>

<script setup lang="ts" name="cmsCateEdit">
import { ref, shallowRef, reactive, computed, onMounted, toRaw } from 'vue';
import type { FormInstance } from 'element-plus';
import { cateDetail, cateAdd, cateEdit, cateAll } from '/@/api/cms/cate';

const dialogRef = ref(null);

const dialogType = ref('add');

const dialogTitle = computed(() => {
	return dialogType.value == 'add' ? '添加栏目' : '编辑栏目';
});

const emit = defineEmits(['submit', 'close']);

const formRef = shallowRef<FormInstance>();

const formData = reactive({
	id: 0,
	name: '',
	pid: 0,
	sort: 0,
	status: 1,
});

const cateOptions = ref([]);

// 获取上级栏目
const setOptionsData = async () => {
	cateOptions.value = await cateAll();
};

const rules = reactive({
	name: [{ required: true, message: '请输入栏目名称', trigger: ['blur'] }],
});

const setFormPid = async (row: any) => {
	formData.pid = row.id;
};

const handleSubmit = async () => {
	await formRef.value?.validate(async (valid: boolean) => {
		if (!valid) return;
		if(!formData.pid) formData.pid = 0;
		dialogType.value == 'add' ? await cateAdd(formData) : await cateEdit(formData);
		dialogRef.value?.close();
		emit('submit');
	});
};

const setFormData = async (row: any, callback: any) => {
	const data = await cateDetail({
		id: row.id,
	});

	for (const key in formData) {
		if (data[key] != null && data[key] != undefined) {
			formData[key] = data[key];
		}
	}
	callback();
};

const handleClose = () => {
	emit('close');
};

const open = (type = 'add') => {
	dialogType.value = type;
	dialogRef.value?.open();
};

onMounted(() => {
	setOptionsData();
});

defineExpose({
	open,
	setFormData,
	setFormPid,
});
</script>
